#!/bin/bash
set -e;

echo "get latest version"
source ../../pi.vars;
default_version=`get_github_latest https://github.com/AdguardTeam/AdGuardHome/releases/latest`




echo "check system......"
case $(uname -m) in
    x86_64)  deploy_sys=amd64;;
    aarch64) deploy_sys=arm64;;
	*) echo "scripts not support system `uname -m`"&&exit ;;
esac



whoname=`whoami`

rm -f /tmp/AdGuardHome_linux_${deploy_sys}.tar.gz;
rm -rf /tmp/AdGuardHome;


adg_v=${default_version}
echo "default: ${adg_v}"


echo "download AdGuardHome......";
wget "${github_proxy}https://github.com/AdguardTeam/AdGuardHome/releases/download/v${adg_v}/AdGuardHome_linux_${deploy_sys}.tar.gz" -O /tmp/AdGuardHome_linux_${deploy_sys}.tar.gz;
tar -xvf /tmp/AdGuardHome_linux_${deploy_sys}.tar.gz -C /tmp/;

sudo mkdir -p /opt/adguardhome/;
sudo chown -R ${whoname}  /opt/adguardhome/;

echo "begin update AdGuardHome......";
if [ -f /opt/adguardhome/AdGuardHome ];then
	cd /opt/adguardhome/;
	sudo ./AdGuardHome -s uninstall||echo "uninstall";

fi


sudo cp -rf /tmp/AdGuardHome/* /opt/adguardhome/;
if [ -f /opt/adguardhome/AdGuardHome.yaml ];then
    echo "skip init AdGuardHome.yaml";
else
    sudo cp AdGuardHome.yaml /opt/adguardhome/;
    cp st*.sh  /opt/adguardhome/;
fi;
echo "begin install AdGuardHome...... "
cd /opt/adguardhome;
pwd;
sudo chmod 755 AdGuardHome;
sudo ./AdGuardHome -s install;
sudo systemctl start AdGuardHome;
sudo systemctl enable AdGuardHome;
